from django import forms
from django.contrib.auth.models import User
from .models import UserProfile

from django.contrib.auth import authenticate
from django.core.exceptions import ValidationError
from blog.models import Post,Category,Tag


class LoginForm(forms.Form):
    username = forms.CharField(label='用户名', max_length=32, widget=forms.TextInput(attrs={
        'class': 'input', 'placeholder': '用户名/邮箱'
    }))
    password = forms.CharField(label='密码', min_length=6, widget=forms.PasswordInput(attrs={
        'class': 'input', 'placeholder': '密码'}))
    
    def clean(self):
        username = self.cleaned_data.get('username')
        password = self.cleaned_data.get('password')

         # 检查用户名和密码是否为空
        if not username or not password:
            raise ValidationError('用户名和密码不能为空。')
        
        # 检查用户名是否存在
        if not User.objects.filter(username=username).exists():
            raise ValidationError('用户名不存在。')
        
         # 尝试认证用户
        user = authenticate(username=username, password=password)

        print(user)
     
        if user:
            if not user.is_active:
                # 用户未激活
                raise ValidationError('账号还未激活，请先激活账号。')
            self.cleaned_data['user'] = user
            return self.cleaned_data
        else:
            # 用户名存在但密码错误或用户不存在
            if User.objects.filter(username=username).exists():
                raise ValidationError('密码错误或者账户未激活。')
            else:
                raise ValidationError('用户名不存在。')

        return self.cleaned_data
            
   

class RegisterForm(forms.ModelForm):
    """注册表单"""
    email = forms.EmailField(label='邮箱', max_length=32, widget=forms.EmailInput(attrs={
        'class': 'input', 'placeholder': '用户名/邮箱'
    }))
    password = forms.CharField(label='密码', min_length=6, widget=forms.PasswordInput(attrs={
        'class': 'input', 'placeholder': '密码'}))
    password1 = forms.CharField(label='再次输入密码', min_length=6, widget=forms.PasswordInput(attrs={
        'class': 'input', 'placeholder': '再次输入密码'}))

    class Meta:
        model = User
        fields = ['email', 'password', 'password1']

    def clean_password(self):
        email = self.cleaned_data.get('email') 
        password = self.cleaned_data.get('password')

        if email  == password:
            raise forms.ValidationError('用户名与密码不能相同！')
        return password

    def clean_email(self):
        """ 验证用户是否存在 """
        email = self.cleaned_data.get('email')
        exists = User.objects.filter(email=email).exists()
        if exists:
            raise forms.ValidationError('用户名已经存在!')
        return email

    def clean_password1(self):
        """验证密码是否相等"""
        if self.cleaned_data['password'] != self.cleaned_data['password1']:
            raise forms.ValidationError('两次密码输入不一致！')
        return self.cleaned_data['password1']


class ForgetPwdForm(forms.Form):
    """ 填写email表单页面 """
    email = forms.EmailField(label='请输入注册邮箱地址', min_length=4, widget=forms.EmailInput(attrs={
        'class': 'input', 'placeholder': '用户名/邮箱'
    }))


class ModifyPwdForm(forms.Form):
    """修改密码表单"""
    password = forms.CharField(label="输入新密码", min_length=6,
        widget=forms.PasswordInput(attrs={'class': 'input', 'placeholder': '输入密码'}))




class UserForm(forms.ModelForm):
    email = forms.EmailField(widget=forms.EmailInput(attrs={
        'class': 'input', 'disabled': 'disabled'
    }))

    class Meta:
        model = User
        fields = ('email',)


class UserProfileForm(forms.ModelForm):
    birthday = forms.DateField(
        widget=forms.DateInput(attrs={'type': 'date'}),
        input_formats=['%Y-%m-%d']
    )

    class Meta:
        model = UserProfile
        fields = ['nike_name', 'desc', 'gexing', 'birthday', 'gender', 'address', 'image']
        widgets = {
            'gender': forms.Select(choices=UserProfile.USER_GENDER_TYPE),
        }





class PostForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = ['title', 'desc', 'category', 'content', 'tags']

    def __init__(self, *args, **kwargs):
        super(PostForm, self).__init__(*args, **kwargs)
        # 确保 category 字段是一个下拉列表
        self.fields['category'] = forms.ModelChoiceField(
            queryset=Category.objects.all(),
            empty_label=None,
        )
        # 确保 tags 字段允许多选
        self.fields['tags'] = forms.ModelMultipleChoiceField(
            queryset=Tag.objects.all(),
            widget=forms.CheckboxSelectMultiple,
            required=False,
        )
